// API服务配置
const BASE_URL = 'http://localhost:1002';

// 请求封装
const request = (url, options = {}) => {
  return new Promise((resolve, reject) => {
    const fullUrl = BASE_URL + url;
    console.log('发起API请求:', {
      url: fullUrl,
      method: options.method || 'GET',
      data: options.data
    });
    
    wx.request({
      url: fullUrl,
      method: options.method || 'GET',
      data: options.data || {},
      header: {
        'Content-Type': 'application/json',
        ...options.header
      },
      success: (res) => {
        console.log('API请求成功:', {
          url: fullUrl,
          statusCode: res.statusCode,
          data: res.data
        });
        if (res.statusCode === 200) {
          resolve(res.data);
        } else {
          reject(new Error(`请求失败: ${res.statusCode}`));
        }
      },
      fail: (err) => {
        console.error('API请求失败:', {
          url: fullUrl,
          error: err
        });
        reject(err);
      }
    });
  });
};


// 通知相关API
const noticeApi = {
  // 获取全部通知
  getAllNotices() {
    return request('/tea/notice/list');
  },
  
  // 添加通知
  addNotice(notice) {
    return request('/tea/notice/add', {
      method: 'POST',
      data: notice
    });
  },

  // 获取通知详情
  getNoticeById(id) {
    return request(`/tea/notice/get/${id}`);
  },

  // 更新通知
  updateNotice(notice) {
    return request('/tea/notice/update', {
      method: 'PUT',
      data: notice
    });
  },

  // 删除通知
  deleteNotice(noticeId) {
    return request(`/tea/notice/delete/${noticeId}`, {
      method: 'DELETE'
    });
  },

  // 获取我发布的通知
  getMyNotices(publisherUserId) {
    return request(`/tea/notice/myNotices/${publisherUserId}`);
  },

  // 获取班级通知
  getClassNotices(classId) {
    return request(`/tea/notice/classNotices/${classId}`);
  },

  // 获取置顶通知
  getTopNotices() {
    return request('/tea/notice/topNotices');
  },

  // 搜索通知
  searchNotices(keyword) {
    return request(`/tea/notice/search?keyword=${keyword}`);
  },

  // 批量删除通知
  batchDeleteNotices(ids) {
    return request('/tea/notice/batchDelete', {
      method: 'DELETE',
      data: ids
    });
  },

  // 设置置顶
  setTop(noticeId, isTop) {
    return request(`/tea/notice/setTop/${noticeId}?isTop=${isTop}`, {
      method: 'PUT'
    });
  }
};

// 班级相关API
const classApi = {
  // 获取全部班级
  getAllClasses() {
    return request('/tea/class/list');
  },

  // 获取班级详情
  getClassById(id) {
    return request(`/tea/class/get/${id}`);
  },

  // 添加班级
  addClass(classData) {
    return request('/tea/class/add', {
      method: 'POST',
      data: classData
    });
  },

  // 更新班级
  updateClass(classData) {
    return request('/tea/class/update', {
      method: 'PUT',
      data: classData
    });
  },

  // 删除班级
  deleteClass(classId) {
    return request(`/tea/class/delete/${classId}`, {
      method: 'DELETE'
    });
  },

  // 获取我的班级
  getMyClasses(creatorUserId) {
    return request(`/tea/class/myClasses/${creatorUserId}`);
  },

  // 根据年级获取班级
  getClassesByGrade(grade) {
    return request(`/tea/class/byGrade/${grade}`);
  },

  // 根据科目获取班级
  getClassesBySubject(subject) {
    return request(`/tea/class/bySubject/${subject}`);
  },

  // 搜索班级
  searchClasses(keyword) {
    return request(`/tea/class/search?keyword=${keyword}`);
  },

  // 获取班主任班级
  getHeadteacherClasses() {
    return request('/tea/class/headteacherClasses');
  },

  // 根据邀请码获取班级
  getClassByCode(classCode) {
    return request(`/tea/class/byCode/${classCode}`);
  }
};

// 用户相关API
const userApi = {
  // 获取全部用户
  getAllUsers() {
    return request('/tea/user/list');
  },

  // 获取用户详情
  getUserById(id) {
    return request(`/tea/user/get/${id}`);
  },

  // 添加用户
  addUser(userData) {
    return request('/tea/user/add', {
      method: 'POST',
      data: userData
    });
  },

  // 更新用户
  updateUser(userData) {
    return request('/tea/user/update', {
      method: 'PUT',
      data: userData
    });
  },

  // 删除用户
  deleteUser(userId) {
    return request(`/tea/user/delete/${userId}`, {
      method: 'DELETE'
    });
  },

  // 根据身份获取用户
  getUsersByIdentity(identity) {
    return request(`/tea/user/byIdentity/${identity}`);
  },

  // 根据手机号获取用户
  getUserByPhone(phone) {
    return request(`/tea/user/byPhone/${phone}`);
  },

  // 搜索用户
  searchUsers(keyword) {
    return request(`/tea/user/search?keyword=${keyword}`);
  },

  // 获取老师列表
  getTeachers() {
    return request('/tea/user/teachers');
  },

  // 获取学生列表
  getStudents() {
    return request('/tea/user/students');
  },

  // 获取家长列表
  getParents() {
    return request('/tea/user/parents');
  },

  // 更新用户头像
  updateAvatar(userId, avatar) {
    return request(`/tea/user/updateAvatar/${userId}?avatar=${avatar}`, {
      method: 'PUT'
    });
  }
};

// 作业相关API
const homeworkApi = {
  // 获取全部作业
  getAllHomework() {
    return request('/tea/homework/list');
  },

  // 获取作业详情
  getHomeworkById(id) {
    return request(`/tea/homework/get/${id}`);
  },

  // 添加作业
  addHomework(homeworkData) {
    return request('/tea/homework/add', {
      method: 'POST',
      data: homeworkData
    });
  },

  // 更新作业
  updateHomework(homeworkData) {
    return request('/tea/homework/update', {
      method: 'PUT',
      data: homeworkData
    });
  },

  // 删除作业
  deleteHomework(homeworkId) {
    return request(`/tea/homework/delete/${homeworkId}`, {
      method: 'DELETE'
    });
  },

  // 获取班级作业
  getClassHomework(classId) {
    return request(`/tea/homework/classHomework/${classId}`);
  },

  // 获取我的作业
  getMyHomework(publisherUserId) {
    return request(`/tea/homework/myHomework/${publisherUserId}`);
  },

  // 获取进行中的作业
  getActiveHomework() {
    return request('/tea/homework/activeHomework');
  },

  // 获取已截止的作业
  getExpiredHomework() {
    return request('/tea/homework/expiredHomework');
  },

  // 搜索作业
  searchHomework(keyword) {
    return request(`/tea/homework/search?keyword=${keyword}`);
  },

  // 设置是否允许修改提交
  setAllowModify(homeworkId, isAllowModify) {
    return request(`/tea/homework/setAllowModify/${homeworkId}?isAllowModify=${isAllowModify}`, {
      method: 'PUT'
    });
  }
};

// 打卡相关API
const checkinApi = {
  // 获取全部打卡活动
  getAllCheckins() {
    return request('/tea/checkin/list');
  },

  // 获取打卡活动详情
  getCheckinById(id) {
    return request(`/tea/checkin/get/${id}`);
  },

  // 添加打卡活动
  addCheckin(checkinData) {
    return request('/tea/checkin/add', {
      method: 'POST',
      data: checkinData
    });
  },

  // 更新打卡活动
  updateCheckin(checkinData) {
    return request('/tea/checkin/update', {
      method: 'PUT',
      data: checkinData
    });
  },

  // 删除打卡活动
  deleteCheckin(checkinId) {
    return request(`/tea/checkin/delete/${checkinId}`, {
      method: 'DELETE'
    });
  },

  // 获取班级打卡活动
  getClassCheckins(classId) {
    return request(`/tea/checkin/classCheckins/${classId}`);
  },

  // 获取我的打卡活动
  getMyCheckins(creatorUserId) {
    return request(`/tea/checkin/myCheckins/${creatorUserId}`);
  },

  // 获取进行中的打卡活动
  getActiveCheckins() {
    return request('/tea/checkin/activeCheckins');
  },

  // 获取已结束的打卡活动
  getExpiredCheckins() {
    return request('/tea/checkin/expiredCheckins');
  },

  // 获取即将开始的打卡活动
  getUpcomingCheckins() {
    return request('/tea/checkin/upcomingCheckins');
  },

  // 搜索打卡活动
  searchCheckins(keyword) {
    return request(`/tea/checkin/search?keyword=${keyword}`);
  }
};

// 成绩相关API
const scoreApi = {
  // 获取全部成绩
  getAllScores() {
    return request('/tea/score/list');
  },

  // 获取成绩详情
  getScoreById(id) {
    return request(`/tea/score/get/${id}`);
  },

  // 添加成绩
  addScore(scoreData) {
    return request('/tea/score/add', {
      method: 'POST',
      data: scoreData
    });
  },

  // 更新成绩
  updateScore(scoreData) {
    return request('/tea/score/update', {
      method: 'PUT',
      data: scoreData
    });
  },

  // 删除成绩
  deleteScore(scoreId) {
    return request(`/tea/score/delete/${scoreId}`, {
      method: 'DELETE'
    });
  },

  // 获取班级成绩
  getClassScores(classId) {
    return request(`/tea/score/classScores/${classId}`);
  },

  // 获取学生成绩
  getStudentScores(studentUserId) {
    return request(`/tea/score/studentScores/${studentUserId}`);
  },

  // 获取科目成绩
  getSubjectScores(subject) {
    return request(`/tea/score/subjectScores/${subject}`);
  },

  // 获取考试成绩
  getExamScores(examName) {
    return request(`/tea/score/examScores/${examName}`);
  },

  // 获取班级科目排名
  getClassSubjectRanking(classId, subject) {
    return request(`/tea/score/classSubjectRanking/${classId}/${subject}`);
  },

  // 获取学生科目历史
  getStudentSubjectHistory(studentUserId, subject) {
    return request(`/tea/score/studentSubjectHistory/${studentUserId}/${subject}`);
  },

  // 搜索成绩
  searchScores(keyword) {
    return request(`/tea/score/search?keyword=${keyword}`);
  },

  // 批量添加成绩
  batchAddScores(scores) {
    return request('/tea/score/batchAdd', {
      method: 'POST',
      data: scores
    });
  },

  // 获取班级平均分
  getClassAverage(classId, subject) {
    return request(`/tea/score/classAverage/${classId}/${subject}`);
  }
};

module.exports = {
  noticeApi,
  classApi,
  userApi,
  homeworkApi,
  checkinApi,
  scoreApi
};
